<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('msg.login.forgetPassword')"
    width="500px"
    :before-close="handleClose"
    @opened="handleOpen">
    <el-form ref="formRef" :model="form" :rules="rules" size="small" label-width="70px">
      <el-form-item :label="$t('msg.common.phone')" prop="phone">
        <el-input v-model="form.phone" v-trim clearable/>
      </el-form-item>
      <el-form-item :label="$t('msg.common.verifyCode')" prop="verifyCode">
        <el-input v-model="form.verifyCode" v-trim clearable maxlength="4">
          <template #append>
            <el-button type="primary" :disabled="verifyCodeBtnDisabled" @click="handleVerifyCode">{{verifyCodeBtnDisabled ? `${second}秒重获` : '获取验证码'}}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('msg.common.password')" prop="password">
        <el-input v-model="form.password" v-trim type="password" clearable/>
      </el-form-item>
      <el-form-item :label="$t('msg.common.confirmPassword')" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" v-trim type="password" clearable/>
      </el-form-item>
    </el-form>
    <template #footer>
        <el-button size="small" @click="handleClose">取消</el-button>
        <el-button :loading="loading" size="small" type="primary" @click="handleConfirm">
          确认
        </el-button>
    </template>
    <div class="tips">
      <div>密码规则：</div>
      <div>必须8~16位，必须数字、大写字母、小写字母和特殊字符四种中任意3种组合而成</div>
      <div>不能使用连续或相同的三位以上数字或者字母组合，如123，456，abc，111，aaa</div>
      <div>不能带有用户名（即是邮箱前缀）</div>
    </div>

  </el-dialog>
</template>

<script setup>
import { computed, defineEmits, defineProps, ref } from 'vue'
import { useDialogCommonData, emitBaseEventList } from '@/composables/dialog-common'
import { validatePassword, validatePhoneRegExp } from '@/utils/commonValidate'
import { awaitWrap, elFormValidate } from '@/utils'
import { forgetPassword, getVerifyCode } from '@/api/login'
import { SUCCESS_CODE } from '@/constants'
import { encryptSHA256 } from '@/utils/encryption'
import { ElMessage } from 'element-plus'
// ---------------------props-------------------
const props = defineProps({
  visible: Boolean // 可见性
})
// emit
const emit = defineEmits([...emitBaseEventList])

// form组件实例
const formRef = ref() // this.$refs.form

// ---------------------el-Dialog组件需要一些参数-------------------
const { dialogVisible, handleClose } = useDialogCommonData(props, emit)

// 打开
const handleOpen = () => {
  formRef.value.resetFields()
}

// ---------------------表单-------------------
const defaultForm = {
  phone: '', // 手机号
  password: '', // 新密码
  confirmPassword: '', // 确认密码
  verifyCode: '' // 验证码
}
const form = ref({ ...defaultForm })
// 表单校验规则
const rules = ref({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: validatePhoneRegExp(), message: '请输入正确的手机号', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (form.value.password === '') {
          callback(new Error('请输入密码'))
        }
        if (value !== form.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// ---------------------验证码-------------------
const verifyCodeBtnDisabled = ref(false)
const second = ref(30)
const handleVerifyCode = () => {
  // 验证手机号
  formRef.value.validateField('phone', async (valid) => {
    if (valid) {
      // 发送验证码
      const { res } = await awaitWrap(getVerifyCode(form.value.phone))
      if (res.statusCode === SUCCESS_CODE) {
        verifyCodeBtnDisabled.value = true
        // 倒计时
        const timer = setInterval(() => {
          if (second.value === 0) {
            clearInterval(timer)
            verifyCodeBtnDisabled.value = false
            second.value = 30
            return
          }
          second.value--
        }, 1000)
      }
    }
  })
}

// ---------------------确认-------------------
const loading = ref(false)
const setParams = () => {
  const { phone, verifyCode, confirmPassword } = form.value
  return {
    phone: phone,
    verificationCode: verifyCode,
    newPassword: encryptSHA256(confirmPassword)
  }
}
const handleConfirm = async () => {
  await elFormValidate(formRef.value)
  const params = setParams()
  loading.value = true
  const { res } = await awaitWrap(forgetPassword(params))
  if (res.statusCode === SUCCESS_CODE) {
    ElMessage.success('修改成功')
    emit('update:visible', false)
    dialogVisible.value = false
  }
  loading.value = false
}

</script>

<style scoped lang="scss">
.tips {
  font-size: 12px;
  color: #ccc;
  margin-left: 10px;
}
</style>
